package com.zb.finance.controller;


import cn.hutool.core.collection.CollectionUtil;
import com.zb.entity.AccounLoginInfo;
import com.zb.entity.ZjWithdraw;
import com.zb.entity.ZjWithdrawBankExchange;
import com.zb.entity.ZjWithdrawRecord;
import com.zb.finance.service.ConWithdrawService;
import com.zb.result.PageUtil;
import com.zb.result.Result;
import com.zb.service.ZjWithdrawLogService;
import com.zb.service.ZjWithdrawRecordService;
import com.zb.service.ZjWithdrawService;
import com.zb.utils.TokenUtil;
import com.zb.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 提现表 前端控制器
 * </p>
 *
 * @author WEN
 * @since 2024-05-27
 */
@Api(tags = "提现类接口")
@RestController
@RequestMapping("/withdraw")
@Slf4j
public class ZjWithdrawController {
    @Resource
    private ConWithdrawService conWithdrawService;
    @Resource
    private ZjWithdrawLogService withdrawLogService;
    @Resource
    private ZjWithdrawService zjWithdrawService;
    @Resource
    private ZjWithdrawRecordService zjWithdrawRecordService;

    @ApiOperation("获取可提现工单列表")
    @PostMapping("/getWithdrawOrderList/{networkId}/{networkEmpId}")
    public Result getWithdrawOrderList(@PathVariable @ApiParam(value = "服务商ID", required = true) Long networkId,
                                       @PathVariable @ApiParam(value = "服务人员ID", required = true) Long networkEmpId,
                                       @RequestBody PageUtil pageUtil) {
        return Result.success("获取可提现工单列表成功").data(conWithdrawService.getWithdrawOrderList(networkId, networkEmpId, pageUtil));
    }

    @ApiOperation("保存提现单")
    @PostMapping("/save")
    public Result save(HttpServletRequest request, @RequestBody @Valid WithdrawVo withdrawVo) {
        AccounLoginInfo loginInfo = TokenUtil.getAccountLoginInfo(request);
        conWithdrawService.save(loginInfo, withdrawVo);
        return Result.success("保存提现单成功");
    }

    @ApiOperation("获取提现单列表")
    @PostMapping("/getList")
    public Result getList(HttpServletRequest request, @RequestBody WithdrawListSearchVo search) {
        Long custAccId = TokenUtil.getcustAccIdByToken(request);
        return Result.success("获取提现列表成功").data(conWithdrawService.getList(custAccId, search));
    }

    @ApiOperation("获取提现单详情")
    @GetMapping("/getDetail/{id}")
    public Result getDetail(@PathVariable @ApiParam(value = "提现单ID", required = true) Long id) {
        return Result.success("获取提现单详情成功").data(PageUtil.row(conWithdrawService.getDetail(id)));
    }

    @ApiOperation("根据提现单ID获取提现工单")
    @GetMapping("/getWithdrawOrder/{id}")
    public Result getWithdrawOrder(@PathVariable @ApiParam(value = "提现单ID", required = true) Long id) {
        return Result.success("获取提现工单成功").data(PageUtil.rows(conWithdrawService.getWithdrawOrder(id)));
    }

    @ApiOperation("根据提现单ID获取操作日志")
    @PostMapping("/getWithdrawLog/{id}")
    public Result getWithdrawLog(@PathVariable @ApiParam(value = "提现单ID", required = true) Long id, @RequestBody PageUtil pageUtil) {
        return Result.success("获取操作日成功").data(withdrawLogService.getWithdrawLogList(id, pageUtil));
    }

    @ApiOperation("获取更改提现单前的查询")
    @GetMapping("/getBeforeUpdateSelect/{id}")
    public Result getBeforeUpdateSelect(@PathVariable @ApiParam(value = "提现单ID", required = true) Long id) {
        return Result.success("获取更改前的提现单成功").data(PageUtil.row(conWithdrawService.getDetail(id)));
    }

    @ApiOperation("审核提现单")
    @PostMapping("/checkWithdraw")
    public Result checkWithdraw(HttpServletRequest request, @RequestBody @Valid CheckWithdrawVo withdrawVo) {
        AccounLoginInfo loginInfo = TokenUtil.getAccountLoginInfo(request);
        conWithdrawService.checkWithdraw(loginInfo, withdrawVo);
        return Result.success("审核成功");
    }

    @ApiOperation("批量完成打款")
    @PostMapping("/finishWithdraw")
    public Result finishWithdraw(HttpServletRequest request, @RequestBody @Valid FinishWithdrawVo withdrawVo) {
        AccounLoginInfo loginInfo = TokenUtil.getAccountLoginInfo(request);
        conWithdrawService.finishWithdraw(loginInfo, withdrawVo);
        return Result.success("完成打款成功");
    }

    @ApiOperation("导出提现单")
    @PostMapping("/exportWithdrawToExcel")
    public void exportWithdrawToExcel(HttpServletRequest request, HttpServletResponse response, @RequestBody WithdrawListSearchVo search) {
        AccounLoginInfo loginInfo = TokenUtil.getAccountLoginInfo(request);
        conWithdrawService.exportWithdrawToExcel(loginInfo, response, search);
    }

    /**
     * 银行推送、处理完成后回调接口
     * @param request Servlet请求上下文
     * @param response Servlet响应上下文
     * @param bankProxyResponse 回调参数
     * @return Boolean是否成功，true表示成功，false表示失败
     * 状态取值变化：3-推送完成 88-推送中 99-推送失败
     * */
    @ApiOperation("银行回调接口")
    @PostMapping("/bankCallback")
    public Result bankCallback(
            HttpServletRequest request,
            HttpServletResponse response,
            @RequestBody BankProxyResponse<TransactionResultNotifiedDingdongResponse> bankProxyResponse
    ) {
        TransactionResultNotifiedDingdongResponse data = bankProxyResponse.getData();
        if (CollectionUtil.isEmpty(data.getWithdrawIds()))return Result.success();

        Set<String> withdrawIds = data.getWithdrawIds();
        List<ZjWithdraw> zjWithdraws = zjWithdrawService.listByIds(withdrawIds);

        if (bankProxyResponse.getCode()==200){
            zjWithdraws.forEach(zjWithdraw -> zjWithdraw.setStatus(3));
            zjWithdrawService.updateBatchById(zjWithdraws);
            List<ZjWithdrawRecord> zjWithdrawRecords = zjWithdrawRecordService.listByIds(withdrawIds);
            zjWithdrawRecords.forEach(zjWithdrawRecord ->
                    zjWithdrawRecord.setCallbackResult("")
                            .setCallbackTime(LocalDateTime.now())
                            .setCreditNo(data.getCreditNo())
            );
            zjWithdrawRecordService.updateBatchById(zjWithdrawRecords);
        }else {
            zjWithdraws.forEach(zjWithdraw -> zjWithdraw.setStatus(99));
            zjWithdrawService.updateBatchById(zjWithdraws);
            List<ZjWithdrawRecord> zjWithdrawRecords = zjWithdrawRecordService.listByIds(withdrawIds);
            zjWithdrawRecords.forEach(zjWithdrawRecord ->
                    zjWithdrawRecord.setCallbackResult(bankProxyResponse.getMessage())
                            .setCallbackTime(LocalDateTime.now())
                            .setCreditNo(null)
            );
            zjWithdrawRecordService.updateBatchById(zjWithdrawRecords);
        }
        return Result.success();
    }

    /**
     * 修改提现单详情接口
     * */
    @ApiOperation("修改提现单详情接口")
    @PostMapping("/updateWithdraw/{id}")
    public Result updateWithdraw(HttpServletRequest request,@PathVariable("id") Long id, @RequestBody @Valid WithdrawDetail withdrawDetail) {
        ZjWithdraw byId = zjWithdrawService.getById(id);
        if (byId==null)return Result.error(50000,"未找到该提现单");
        byId.setBankNo(withdrawDetail.getBankNo());
        byId.setOpeningBank(withdrawDetail.getOpeningBank());
        byId.setCardholderName(withdrawDetail.getCardholderName());
        byId.setApplyRemark(withdrawDetail.getApplyRemark());
        byId.setName(withdrawDetail.getName());
        zjWithdrawService.updateById(byId);
        return Result.success("修改成功");
    }
}
